package com.hhq.demo.filter;

import com.hhq.demo.bean.User;
import com.hhq.demo.utils.UserUtil;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author HHQ
 * @date 2021年12月17日
 */
@WebFilter({"/main.html","/views/*","/express/*","/user/*","/courier/*"})
public class AccessControllerFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        String userName = UserUtil.getUserName(req.getSession());
        User wxUserInfo = UserUtil.getWxUserInfo(req.getSession());
        resp.setContentType("text/html;charset=UTF-8");
        if(userName != null) {
            filterChain.doFilter(req, resp);
        } else {
            PrintWriter writer = resp.getWriter();
            writer.println("<script>alert('请登录后再进行操作！');top.location.href='/login.html'</script>");
        }

    }

    @Override
    public void destroy() {

    }
}
